/**
 * @author zhangqiang
 * @date   17/7/20
 */
import React, {Component} from 'react'
import {connect} from 'react-redux'
import {Toast, Modal} from 'antd-mobile'
import {
	getPeccDetail,
	prepareUserOrder,
	payMent,
	weixinQuery
} from '../../actions/payMentAction'
import {OrderList, SelectPayMent} from '../../components/payment'
import '../../../styles/payment.scss'
import style from './index.scss'
import common from '../../../../../../js/utils/common'
import typeOfBrowser from '../../../../../../js/utils/typeOfBrowser'
const alert = Modal.alert;

class Payment extends Component {
	constructor(props) {
		super(props);
		this.state = {
			payType: this.props.payType[0], //默认支付类型
			chargeOrderId: '',
			isIPhoneHideWX: false
		}
		this.backendIds = sessionStorage.getItem('illegal_backendIds');
		this.violationIds = sessionStorage.getItem('illegal_violationIds');
		this.carId = sessionStorage.getItem('illegal_carId');
	}

	componentWillMount() {
		if(sessionStorage.getItem('payType')){
			this.setState({
				payType: JSON.parse(sessionStorage.getItem('payType'))
			})
		}
	}

	componentDidMount() {
		common.setViewTitle('订单确认');
		if(common.isIPhone()){
			this.setState({
				isIPhoneHideWX: true
			})
		}
		let postData = {
			violationIds: this.violationIds,
			carId: this.carId 
		}
		this.props.dispatch(getPeccDetail(postData))
		this.props.dispatch(prepareUserOrder({
			carId: this.carId,
			violationIds: this.violationIds, 
			backendIds: this.backendIds, 
			couponId: '',
			isUrgent: true,
			phone: ""
		}))
		
		if(sessionStorage.getItem('weixinPay')){
			alert('', <div style={{fontSize: '.32rem'}}>请确定微信支付是否已完成
					<img onClick={()=>{
						common.closeAliModal()
						this.weixinNewsCallback()	//不用调到成功页				
					}} 
					className='maskClose' src="./images/icon-close.png" alt=""/>
				</div>, [
				{
					text: '已完成支付',
					onPress: () =>{
						this.weixinNewsCallback()
					},
					style: {color: 'red',fontSize: '.3rem'}
				},
				{ text: '支付遇到问题，重新支付', onPress: () => {
					sessionStorage.removeItem('weixinPay')
					this.orderPay()
				}, style: {color: '#333',fontSize: '.3rem'}},
				{ text: '取消支付', onPress: () => console.log('第0个按钮被点击了') ,style:{display: 'none'}},
			])
		}
	}

	componentWillUnmount() {
	}

	/**
	 * 设置支付类型
	 * @param type 支付类型
	 */
	setPayType(type) {
		sessionStorage.setItem('payType',JSON.stringify(type))
		this.setState({
			payType: type
		})
	}

	//渲染支付方式
	renderPayTypes() {
		let isIPhoneHideWX;
		return this.props.payType.map((item, i) => {
			if ((this.state.isIPhoneHideWX&&i==1) || (typeOfBrowser.getChannelOfBrowser() == 'weixin'&&i==0)) {  //默认 true   苹果环境隐藏微信
				isIPhoneHideWX = true;
			} else {
				isIPhoneHideWX = false;
			}
	
			return <div key={i} className={style.verCenter} onClick={type => this.setPayType(item)} style={isIPhoneHideWX?{display:'none'}:{}}>
				<img className={style.pay_type_icon} src={item.icon}/>
				<div className={style.title}>{item.title}</div>
				<img className={style.pay_type_select_icon}
					src={this.state.payType.name == item.name ? './images/select-true.png' : './images/select-false.png'}/>
			</div>
		})
	}

	//订单列表
	renderOrderList() {
		return this.props.peccDetail.map((item,index)=>{
			return <OrderList data = {item} key ={index}/>
		})
	}
	/** 
	 *  微信支付回调查询用户是否支付
	 * /*
    微信查询状态码
   	SUCCESS—支付成功
	REFUND—转入退款
	NOTPAY—未支付
	CLOSED—已关闭
	REVOKED—已撤销（刷卡支付）
	USERPAYING--用户支付中
	PAYERROR--支付失败(其他原因，如银行返回失败)
	*/
	weixinNewsCallback(){
		let wxData = sessionStorage.getItem('wxData'),
			forwardUrl = sessionStorage.getItem('forwardUrl');

		this.props.dispatch(weixinQuery({
			chargeOrderId:  wxData
		}, (result) => {
			if (result.payStatus == 'SUCCESS'){
				location.href = forwardUrl
			}
			sessionStorage.removeItem('weixinPay')
			sessionStorage.removeItem('wxData')
			sessionStorage.removeItem('forwardUrl')
		}))
	}

	toUrl(url) {
		this.context.router.replace(url);
	}
	  
	orderPay() {
		//http://14.23.146.234:7000/emsc-partner/b/o/wxAuth?chargeOrderId=TEST108180112000001
		let isWXBrowser = false;
		if (typeOfBrowser.getChannelOfBrowser() == 'weixin') {
			isWXBrowser = true
			this.setState({
				payType: this.state.payType['type'] = 4
			})
		} else {
			isWXBrowser = false
		}
		let postData = {
			carId: this.carId,
            violationIds: this.violationIds, 
            couponId: '',
            backendIds: this.backendIds,
            payType: this.state.payType.type, 
            isUrgent: true,
            phone: ""
		}

		this.props.dispatch(payMent(postData, isWXBrowser, (resultData) => {
			console.log(resultData.payOrderId)
			if (isWXBrowser) {
				window.location.href = `https://test-emsc.cx580.com/emsc-partner/b/o/wxAuth?chargeOrderId=${resultData.payOrderId}` //TEST108180112000001
			} else {
				window.location.href = resultData;
			}
		}))
	}

	render() {
		return (
			<div className={style.payment}>
				<div style={{height: '.3rem'}}></div>
				{
					this.renderOrderList()
				}
				<div className={style.total}>
					<span>总计</span>
					<span>¥{this.props.payMent}</span>
				</div>
				<div style={{height: '.3rem'}}></div>
				<div className={style.payType}>
					{
						this.renderPayTypes()
					}
				</div>
				<div className={style.listFooter}>
					本次办理不提供发票，如需发票，请联系邮政速递客服：020-11183-6
				</div>
				<div style={{height: '1.24rem'}}></div>
				<div className={style.pay_button_box}>
					<div className={style.pay_money}>
						<span>总计：</span>
						<span>￥{this.props.payMent}</span>
					</div>
					<button className={style.pay_button} onClick={()=>{this.orderPay()}}>立即支付</button>
				</div>
			</div>
		)
    }
}

//使用context
Payment.contextTypes = {
    router: React.PropTypes.object.isRequired
};

Payment.defaultProps = {
	peccDetail: [],
	payType: [
		{
			name: 'alipay',
			title: '支付宝支付',
			icon: './images/alipay-icon.png',
			type: '2',
		}, {
			name: 'weixin',
			title: "微信支付",
			icon: './images/weixin-icon.png',
			type: '3',
		}
	],
};

function mapStateToProps(state) {
    return Object.assign({}, state.payMentInfo);
}

export default connect(mapStateToProps)(Payment);
